import { Component, OnInit, ContentChild, Input, OnChanges, SimpleChanges, AfterContentChecked, HostBinding, Inject, OnDestroy, Optional } from '@angular/core';

import { ViewHeaderComponent } from './view-header/view-header.component';
import { ViewMainComponent } from './view-main/view-main.component';
import { BaseView } from '../../core/view/base-view';
import { SPA, VIEW_HEADER_FIXED } from '../../core/keys';
import { Subscription } from 'rxjs';

@Component({
  selector: 'bz-view',
  templateUrl: './view.component.html',
})
export class ViewComponent<U, B, S> extends BaseView<U, B, S> implements OnInit, OnChanges, AfterContentChecked, OnDestroy {

  @Input() bzTitle: string;
  @Input() @HostBinding('class.header-fixed') bzHeaderFixed: boolean;

  @ContentChild(ViewHeaderComponent, { static: true }) viewHeader: ViewHeaderComponent;
  @ContentChild(ViewMainComponent, { static: true }) viewMain: ViewMainComponent<U, B, S>;

  private viewHeightChange$: any;
  private heightChangeSub: Subscription[] = [];

  constructor(@Inject(VIEW_HEADER_FIXED) viewHeaderFixed: boolean) {
    super();
    // this.spa = this.spa === null ? false : this.spa;
    this.bzHeaderFixed = viewHeaderFixed;
  }

  ngOnInit() {

  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.bzTitle) {
      this.broadcastService.emit(<any>'NavTabTitle', changes.bzTitle.currentValue);
    }
  }

  ngAfterContentChecked(): void {
    if (!this.bzHeaderFixed) {
      return;
    }

    // bz-view-header 组件重新挂载到DOM上
    if (this.viewHeader && this.viewHeader.heightChange$ !== this.viewHeightChange$) {
      this.viewHeightChange$ = this.viewHeader.heightChange$;
      const sub = this.viewHeightChange$.subscribe((height) => {
        // if (this.spa && height === 0) {
        //   height = +height + 12;
        // }
        this.viewMain.ele.nativeElement.style.top = `${height}px`;
        this.viewMain.ele.nativeElement.style.height = `calc(100% - ${height}px)`;
      });
      this.heightChangeSub.push(sub);
      this.viewHeader.watchHeight();
    } else if (!this.viewHeader && this.viewHeightChange$ !== null) {// bz-view-header 从DOM中移除
      this.viewMain.ele.nativeElement.style.top = '0px';
      this.viewMain.ele.nativeElement.style.height = '100%';
      this.viewHeightChange$ = null;
    }
  }

  ngOnDestroy(): void {
    this.heightChangeSub.forEach(sub => {
      sub.unsubscribe();
    });
  }
}
